package com.lbh.music.lyric;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.protocol.HTTP;

import com.lbh.music.activity.Music;
import com.lbh.music.activity.PreferenceService;
import com.lbh.music.service.MusicService;

import android.util.Log;

public class SearchLRC {

	// 百度搜索歌 接口
	public static final String SearchLrcApi = "http://box.zhangmen.baidu.com/x?op=12&count=1&title=";
	private URL url;
	StringBuffer sb = new StringBuffer();
	private boolean findNumber = false;
	private Music mMusic;
	private String musicName;
	private String singerName;
	private String saveLrcPaht;
	public static boolean DOWN_FINISH = false;

	/*
	 * 初期化，根据参数取得lrc的地址
	 */
	// public SearchLRC(String musicName, String singerName) {
	public SearchLRC(Music music) {
		this.mMusic = music;
		// 将空格替换成+号
		// musicName = musicName.replace(' ', '+');
		// singerName = singerName.replace(' ', '+');
		// 传进来的如果是汉字，那么就要进行编码转化
		try {
			musicName = URLEncoder.encode(mMusic.getTitle(), "utf-8");
			singerName = URLEncoder.encode(mMusic.getSinger(), "utf-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		String strUrl = SearchLrcApi + musicName + "$$" + singerName + "$$$$";
		Log.v("strUrl", "strUrl:" + strUrl);
		try {
			url = new URL(strUrl);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		BufferedReader br = null;
		String s;
		try {
			HttpURLConnection httpConn = (HttpURLConnection) url
					.openConnection();
			httpConn.connect();
			InputStreamReader inReader = new InputStreamReader(
					httpConn.getInputStream(), "GB2312");
			br = new BufferedReader(inReader);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			while ((s = br.readLine()) != null) {
				sb.append(s + "/r/n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * 根据lrc的地址: 1.保存歌词到本地 2.读取lrc文件流 生成歌词的ArryList 每句歌词是一个String
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ArrayList fetchLyric() {
		int begin = 0, end = 0, number = 0;// number=0表示暂无歌词
		String strid = "";
		begin = sb.indexOf("<lrcid>");
		Log.d("test", "sb = " + sb);
		if (begin != -1) {
			end = sb.indexOf("</lrcid>", begin);
			strid = sb.substring(begin + 7, end);
			number = Integer.parseInt(strid);
			SetFindLRC(number);
		}
		String geciURL = "http://box.zhangmen.baidu.com/bdlrc/" + number / 100
				+ "/" + number + ".lrc"; // 下载lrc地址
		Log.v("SearchLrc", "geciURL: path" + geciURL);

		saveLrcPaht = mMusic.getUrl(); // 获取歌词 存储路劲
		for (int i = saveLrcPaht.length(); i >= 0; i--) {
			if (!saveLrcPaht.substring(saveLrcPaht.length() - 1,
					saveLrcPaht.length()).equals("/")) {
				saveLrcPaht = saveLrcPaht
						.substring(0, saveLrcPaht.length() - 1);
			}
		}

		Log.v("SearchLrc", "SearchLrc: path" + saveLrcPaht);
		ArrayList gcContent = new ArrayList();
		String s = new String();
		try {
			url = new URL(geciURL);
		} catch (MalformedURLException e2) {
			e2.printStackTrace();
		}
		String lrcName = saveLrcPaht
				+ mMusic.getName().trim().replace(".mp3", "") + ".lrc";
		Log.v("SearchLrc", "saveLrcPaht" + saveLrcPaht);
		Log.v("SearchLrc", "lrcName" + mMusic.getTitle());
		Log.v("SearchLrc", "lrcName(歌词路径和名字):" + lrcName);
		// File file = new File(lrcName);
		// if (file.exists()) {
		// file.delete();
		// }
		// 将歌词文件存入 目录
		try {
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			if (connection.getResponseCode() == 200 && findNumber) {
				InputStream istream = connection.getInputStream();

				File dir = new File(saveLrcPaht);
				dir.mkdir();
				File file = new File(lrcName);
				file.createNewFile(); // 创建 歌词文件

				OutputStream output = new FileOutputStream(file);
				byte[] buffer = new byte[1024 * 4];
				while (istream.read(buffer) != -1) {
					output.write(buffer);
				}
				output.flush();
				output.close();
				istream.close();
				DOWN_FINISH = true;
			}
		} catch (Exception e) {
			Log.e("SearchLrc", "SearchLrc(SaveLrc):" + e.toString());
		}
		// 存入List
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(url.openStream(),
					"GB2312"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		if (br == null) {
			System.out.print("stream is null");
		} else {
			try {
				while ((s = br.readLine()) != null) {
					// s = s.replace("[", "");
					// s = s.replace("]", "@");
					gcContent.add(s);
				}
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return gcContent;
	}

	private void SetFindLRC(int number) {
		if (number == 0)
			findNumber = false;
		else
			findNumber = true;
	}

	public boolean GetFindLRC() {
		return findNumber;
	}
}